package com.hjn.springboot.springbootinterceptor.timer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author huaijn
 * @date 2022/5/5 /0005-13:29
 * @description todo
 */
public class ExcutorsTest {

  public static void main(String[] args) {
//    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5);
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
    scheduledExecutorService.scheduleWithFixedDelay(() -> {
      System.out.println(LocalDateTime.now().toString());
    }, 3, 2, TimeUnit.SECONDS);
  }
  /**
   * @param time 每天几点执行定时任务   24小时制时间 例: 08:00:00  20:00:00
   * @throws ParseException
   */
  private void timing(String time) throws ParseException, ParseException {
    /*转换成整时间，小时*/
    int hour = Integer.parseInt(time.substring(0, 2));

    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 获取当前小时
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    int currentHour = calendar.get(Calendar.HOUR_OF_DAY);

    long delayTime;
    long currentTime = System.currentTimeMillis();

    if (currentHour < hour) {
      // 延时时间 = 当天8点-当前时间
      String currentDay = format1.format(new Date());
      long currentDay8 = format2.parse(currentDay + " " + time).getTime();
      delayTime = currentDay8 - currentTime;
    } else if (currentHour == hour) {
      delayTime = 0;
    } else {
      // 延时时间 = 明天8点-当前时间
      Date date = new Date();
      Calendar c = Calendar.getInstance();
      c.setTime(date);
      c.add(Calendar.DATE, 1);

      String nextDay = format1.format(c.getTime());
      long nextDay8 = format2.parse(nextDay + " " + time).getTime();
      delayTime = nextDay8 - currentTime;
    }

    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        //TODO 执行任务
      }
    };

    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
    scheduledExecutorService.scheduleWithFixedDelay(task, delayTime,24 * 60 * 60 * 1000, TimeUnit.SECONDS);
  }
}
